package com.app.qtjk.lsh.service;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.app.common.dataDictionary.DE.DE_USERID;
import com.app.common.dataDictionary.DE.DE_USERPRIZE_ID;
import com.app.common.dataDictionary.DE.DE_USERPRIZE_SFUSED;
import com.app.common.dataDictionary.PO.TUserPrizePO;
import com.app.common.utils.CollectionUtil;
import com.app.common.utils.DateFormatUtil;
import com.app.common.utils.ReqJsonUtil;
import com.app.common.utils.StringUtil;
import com.css.sword.kernel.base.annotation.Service;
import com.css.sword.kernel.base.annotation.ServiceContainer;
import com.css.sword.kernel.base.persistence.IPersistenceService;
import com.css.sword.kernel.base.persistence.SQLParam;
import com.css.sword.kernel.utils.SwordLogUtils;
import com.css.sword.kernel.utils.SwordPersistenceUtils;
import com.css.sword.platform.web.event.IReqData;
import com.css.sword.platform.web.event.IResData;
import com.css.sword.platform.web.event.SwordRes;

@ServiceContainer
public class UserPrizeService {

	private static SwordLogUtils log = SwordLogUtils.getLogger(UserPrizeService.class);

	public UserPrizeService() throws Exception {
		super();
	}

	/**
	 * 获取用户奖品列表
	 * @param req
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Service(serviceName = "UserService_userPrizeList")
	public IResData userPrizeList(IReqData req) throws Exception {

		log.debug("开始进入 UserService_userPrizeList 方法。");

		IPersistenceService dao = SwordPersistenceUtils.getPersistenceService();

		IResData res = new SwordRes();
		HashMap commonMap = new HashMap();
		ArrayList commonList = new ArrayList();
		HashMap hashMap = new HashMap();
		try {
			SQLParam sqlParam = new SQLParam();
			// 获取前台post的数据
			String userId=ReqJsonUtil.getPostParam(req, "userId");
			sqlParam.addParam(userId);
			List<Map<String, Object>> userPrizeMapList = dao.queryMapListByKey("UserService_getUserPrizeList", sqlParam);
			SQLParam param = new SQLParam();
			for (int i = 0; i < userPrizeMapList.size(); i++) {
				Map<String, Object> map = userPrizeMapList.get(i);
				if ("02".equals(map.get("userprizeCategory"))) {
					param.clearParams();
					param.addParam(StringUtil.parse2String(map.get("userprizeId")));
					map.put("uSwddId", dao.queryColumnByKey("UserService_getSwddId", param, 1));
				}
				int userprizeExpirydate = (Integer) map.get("userprizeExpirydate");
				Date userprizeDuihuantime = (Date) map.get("userprizeDuihuantime");
				//计算用户兑换后奖品的有效天数，是动态的（与当前时间作对比计算出来的）
				String userprizeDuihuantimestr = DateFormatUtil.date2str(userprizeDuihuantime,DateFormatUtil.DATE_FORMAT);
				int quotInt = DateFormatUtil.getNowDateQuot(userprizeDuihuantimestr);
				int userprize_validity = userprizeExpirydate - quotInt;
				userPrizeMapList.get(i).put("userprizeValidity",userprize_validity);
				userPrizeMapList.get(i).put("userprizeDuihuantime",userprizeDuihuantimestr);
			}

			hashMap.put("returnStatus", "true");
			hashMap.put("msg", "成功返回，未出现异常！");
			commonMap.put("userPrizeMapList", userPrizeMapList);
		} catch (Exception e) {
			log.debug("---------------系统发生异常！---------------");
			e.printStackTrace();
			hashMap.put("returnStatus", "false");
			hashMap.put("msg", "出现异常！");
		}finally{
			commonMap.put("commonData", hashMap);
			commonList.add(commonMap);
			res.addListWithDataName("returnData", commonList);
		}
		
		return res;
	}

	/**
	 * 用户查看我的奖品详情
	 * @param req
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Service(serviceName = "UserService_userPrizeDetail")
	public IResData userPrizeDetail(IReqData req) throws Exception {

		log.debug("开始进入 UserService_userPrizeDetail 方法。");

		IPersistenceService dao = SwordPersistenceUtils.getPersistenceService();

		IResData res = new SwordRes();
		HashMap commonMap = new HashMap();
		ArrayList commonList = new ArrayList();
		HashMap hashMap = new HashMap();
		try {
			SQLParam sqlParam = new SQLParam();
			// 获取前台post的数据
			String userprizeId = ReqJsonUtil.getPostParam(req, "userprizeId");
			String userId =  ReqJsonUtil.getPostParam(req, "userId");
			sqlParam.addParam(userId);
			sqlParam.addParam(userprizeId);
			Map<String, Object> userprizeDetailMap = dao.queryMapByKey("UserService_getUserPrizeDetail", sqlParam);
			if (CollectionUtil.isNotBlankMap(userprizeDetailMap)) {
				//计算用户兑换后奖品的有效天数，是动态的（与当前时间作对比计算出来的）
				String userprizeDuihuantimestr = DateFormatUtil.date2str((Date) userprizeDetailMap.get("userprizeDuihuantime"),DateFormatUtil.DATE_FORMAT);
				int quotInt = DateFormatUtil.getNowDateQuot(userprizeDuihuantimestr);
				int userprize_validity = (Integer) userprizeDetailMap.get("userprizeExpirydate") - quotInt;
				userprizeDetailMap.put("userprizeValidity", userprize_validity);
				
				String userprizeSfused = StringUtil.parse2String(userprizeDetailMap.get("userprizeSfused"));
				//当奖品未使用时查询奖品详情的sql一样
				if ("0".equals(userprizeSfused)) {
					if (!"".equals(userprize_validity) && userprize_validity > 0) {
						userprizeDetailMap.put("userprizeSfkuse", "1");
					} else {
						userprizeDetailMap.put("userprizeSfkuse", "0");
					}
				}
				//当奖品已使用时,并且奖品类别为02即实物订单类奖品时，查询sql改变一下,因为要多查实物订单表的信息
				if ("1".equals(userprizeSfused)) {
					userprizeDetailMap.put("userprizeSfkuse", "0");
					if ("02".equals(StringUtil.parse2String(userprizeDetailMap.get("userprizeCategory")))) {
						userprizeDetailMap = dao.queryMapByKey("UserprizeOrderService_getSwOrderPrizeDetail", sqlParam);
					}
				}
				commonMap.put("userprizeDetailMap", userprizeDetailMap);
				hashMap.put("returnStatus", "true");
				hashMap.put("msg", "成功返回，未出现异常！");
			} else {
				hashMap.put("returnStatus", "false");
				hashMap.put("msg", "用户奖品不存在！");
			}
		} catch (Exception e) {
			log.debug("---------------系统发生异常！---------------");
			e.printStackTrace();
			hashMap.put("returnStatus", "false");
			hashMap.put("msg", "出现异常！");
		} finally {
			commonMap.put("commonData", hashMap);
			commonList.add(commonMap);
			res.addListWithDataName("returnData", commonList);
		}
		
		return res;
	}

	/**
	 * 用户使用奖品（对于奖品类别是01的来说）
	 * @param req
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Service(serviceName = "UserService_userUsePrize")
	public IResData userUsePrize(IReqData req) throws Exception {

		log.debug("开始进入 UserService_userUsePrize 方法。");

		IPersistenceService dao = SwordPersistenceUtils.getPersistenceService();
		dao.getTransactionService().setAutoCommit(false);

		IResData res = new SwordRes();
		HashMap commonMap = new HashMap();
		ArrayList commonList = new ArrayList();
		HashMap hashMap = new HashMap();
		try {
			SQLParam sqlParam = new SQLParam();
			// 获取前台post的数据
			String userprizeId = ReqJsonUtil.getPostParam(req, "userprizeId");
			String userId =  ReqJsonUtil.getPostParam(req, "userId");
			String wPrizeId =  ReqJsonUtil.getPostParam(req, "wPrizeId");
			sqlParam.addParam(userId);
			sqlParam.addParam(userprizeId);

			Map<String, Object> userprizeDetailMap = dao.queryMapByKey("UserService_getUserPrizeDetail", sqlParam);
			if (CollectionUtil.isNotBlankMap(userprizeDetailMap)) {
				String userprizeSfused = StringUtil.parse2String(userprizeDetailMap.get("userprizeSfused"));
				if ("1".equals(userprizeSfused)) {
					hashMap.put("useSuccess", "false");
					hashMap.put("reason", "该奖品已被使用！");
				} else {
					TUserPrizePO tUserPrizePO = new TUserPrizePO();
					tUserPrizePO.setUserprizeId(new DE_USERPRIZE_ID(userprizeId));
					tUserPrizePO.setUserid(new DE_USERID(userId));
					tUserPrizePO.setUserprizeSfused(new DE_USERPRIZE_SFUSED("1"));
					dao.updatePO(tUserPrizePO);
					hashMap.put("useSuccess", "true");
					//给对应的奖品增加使用次数用来统计
					sqlParam.clearParams();
					sqlParam.addParam(wPrizeId);
					dao.executeByKey("PrizeService_updateSycs", sqlParam);
				}
				hashMap.put("returnStatus", "true");
				hashMap.put("msg", "成功返回，未出现异常！");
			} else {
				hashMap.put("returnStatus", "false");
				hashMap.put("msg", "用户奖品不存在！");
			}
			dao.commitAll();
		} catch (Exception e) {
			dao.rollbackAll();
			log.debug("---------------系统发生异常！---------------");
			e.printStackTrace();
			hashMap.put("returnStatus", "false");
			hashMap.put("msg", "出现异常！");
		} finally {
			commonMap.put("commonData", hashMap);
			commonList.add(commonMap);
			res.addListWithDataName("returnData", commonList);
		}
		return res;
	}

	/**
	 * 用户对已使用过的奖品进行删除
	 * @param req
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Service(serviceName = "UserService_userDeletePrize")
	public IResData userDeletePrize(IReqData req) throws Exception {

		log.debug("开始进入 UserService_userDeletePrize 方法。");

		IPersistenceService dao = SwordPersistenceUtils.getPersistenceService();

		IResData res = new SwordRes();
		HashMap commonMap = new HashMap();
		ArrayList commonList = new ArrayList();
		HashMap hashMap = new HashMap();
		try {
			SQLParam sqlParam = new SQLParam();
			// 获取前台post的数据
			String userprizeId = ReqJsonUtil.getPostParam(req, "userprizeId");
			String userId =  ReqJsonUtil.getPostParam(req, "userId");
			sqlParam.addParam(userId);
			sqlParam.addParam(userprizeId);

			Map<String, Object> userprizeDetailMap = dao.queryMapByKey("UserService_getUserPrizeDetail", sqlParam);
			if (CollectionUtil.isNotBlankMap(userprizeDetailMap)) {
				TUserPrizePO tUserPrizePO = new TUserPrizePO();
				tUserPrizePO.setUserprizeId(new DE_USERPRIZE_ID(userprizeId));
				tUserPrizePO.setUserid(new DE_USERID(userId));
				dao.deletePO(tUserPrizePO);
				hashMap.put("deleteSuccess", "true");
				hashMap.put("returnStatus", "true");
				hashMap.put("msg", "成功返回，未出现异常！");
			} else {
				hashMap.put("deleteSuccess", "false");
				hashMap.put("returnStatus", "true");
				hashMap.put("msg", "奖品不存在或奖品已被用户删除！");
			}
		} catch (Exception e) {
			log.debug("---------------系统发生异常！---------------");
			e.printStackTrace();
			hashMap.put("returnStatus", "false");
			hashMap.put("msg", "出现异常！");
		} finally {
			commonMap.put("commonData", hashMap);
			commonList.add(commonMap);
			res.addListWithDataName("returnData", commonList);
		}
		return res;
	}


}